using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;

using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using UKVSTS;


namespace IEeee
{
    public partial class ServerConfigForm : Form
    {

        private WorkItemType m_SelectedWorkItemType;

        //public WorkItemType SelectedWorkItemType
        //{
        //    get { return m_SelectedWorkItemType; }
        //    set { m_SelectedWorkItemType = value; }
        //}

        public ServerConfigForm ()
        {
            InitializeComponent ();
        }

        private TeamFoundationServer SelectedServer
        {
            get
            {
                return cmbServers.SelectedItem as TeamFoundationServer;
            }
        }

        private Project SelectedProject
        {
            get
            {
                Project selectedProject = null;
                TeamFoundationServer server = SelectedServer;
                if (server != null)
                {
                    NamedWrapper<Project> wrapper = cmbProjects.SelectedItem as NamedWrapper<Project>;
                    if (wrapper != null)
                    {
                        selectedProject = wrapper.Item;
                    }
                }
                return selectedProject;
            }
        }

        private void ServerConfig_Load (object sender, EventArgs e)
        {
            PopulateServerList();
        }

        private void PopulateServerList()
        {
            Cursor oldCursor = Cursor.Current;
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                cmbServers.Enabled = false;
                cmbProjects.Enabled = false;
                cmbWorkItemTypes.Enabled = false;

                cmbServers.Items.Clear();

                TeamFoundationServer[] registeredServers = RegisteredServers.GetServers();

                foreach (TeamFoundationServer server in registeredServers)
                {
                    cmbServers.Items.Add(server);
                }

                cmbServers.Enabled = true;

            }
            catch (Exception ex)
            {
                IEeeeException.DisplayError(this, ex);
            }
            finally
            {
                Cursor.Current = oldCursor;
            }
        }

        private void cmbServers_SelectedIndexChanged (object sender, EventArgs e)
        {
            Cursor oldCursor = Cursor.Current;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                cmbProjects.Enabled = false;
                cmbWorkItemTypes.Enabled = false;

                cmbProjects.Items.Clear();
                cmbWorkItemTypes.Items.Clear();

                TeamFoundationServer server = cmbServers.SelectedItem as TeamFoundationServer;

                String serverName = server.Name;
                UICredentialsProvider uiCredProvider = new UICredentialsProvider();

                server = TeamFoundationServerFactory.GetServer(serverName, uiCredProvider);

                server.Authenticate();

                Debug.Assert(server != null);

                WorkItemStore store = server.GetService(typeof(WorkItemStore)) as WorkItemStore;

                foreach (Project proj in store.Projects)
                {
                    cmbProjects.Items.Add(new NamedWrapper<Project>(proj, proj.Name));

                }

                cmbProjects.Enabled = true;
                cmbProjects.Focus();

                cmbServers.Enabled = true;
            }
            catch (Microsoft.TeamFoundation.WorkItemTracking.Client.UnexpectedErrorException uex)
            {
                String msg = "An unexpected error has occured.\n" +
                             "This might be caused if you are running IE7 in protected mode on Windows Vista.\n" +
                             "To fix this, please add the site, you are raising a bug against, to your trusted sites list.\n" +
                             "Error Details";
                IEeeeException.DisplayError(this, msg, uex);
            }
            catch (Exception ex)
            {
                IEeeeException.DisplayError(this, ex);
            }
             finally
            {
                Cursor.Current = oldCursor;
            }

        }

        private void cmbProjects_SelectedIndexChanged (object sender, EventArgs e)
        {
            Cursor oldCursor = Cursor.Current;


            try
            {
                Cursor.Current = Cursors.WaitCursor;

                cmbWorkItemTypes.Enabled = false;

                cmbWorkItemTypes.Items.Clear ();

                if (SelectedProject != null)
                {
                    int i = 0;
                    int bugIndex = -1;
                    foreach (WorkItemType wiType in SelectedProject.WorkItemTypes)
                    {
                        if (wiType.Name.Equals ("Bug"))
                        {
                            bugIndex = i;
                        }
                        cmbWorkItemTypes.Items.Add (new NamedWrapper <WorkItemType>(wiType, wiType.Name));

                        i++;
                    }

                    cmbWorkItemTypes.SelectedIndex = bugIndex;
                }

                cmbWorkItemTypes.Enabled = true;
                cmbWorkItemTypes.Focus ();

            }
            catch (Exception ex)
            {
                IEeeeException.DisplayError(this, ex);
            }
            finally
            {
                Cursor.Current = oldCursor;
            }


        }

        private void cmbWorkItemTypes_SelectedIndexChanged (object sender, EventArgs e)
        {
            Cursor oldCursor = Cursor.Current;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                NamedWrapper<WorkItemType> wrappedWiType = cmbWorkItemTypes.SelectedItem as NamedWrapper<WorkItemType>;

                m_SelectedWorkItemType = wrappedWiType.Item;
            }
            catch (Exception ex)
            {
                IEeeeException.DisplayError(this, ex);
            }
            finally
            {
                Cursor.Current = oldCursor;
            }

        }

        private void cmdOK_Click (object sender, EventArgs e)
        {
        }

        private void ServerConfigForm_FormClosing (object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
            {
                NamedWrapper<WorkItemType> wrappedWiType = cmbWorkItemTypes.SelectedItem as NamedWrapper<WorkItemType>;

                if (wrappedWiType.Item == null)
                {
                    MessageBox.Show (this, "Please configure the type of Work Item you wish to create.",
                                     "Server Config", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.Cancel = true;
                }
                else
                {
                    IEeeeConfig.Instance.ConfigureForWiType (wrappedWiType.Item);
                }
            }
        }

        private void cmdAdd_Click(object sender, EventArgs e)
        {
            using (AddNewServer dialog = new AddNewServer())
            {
                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    // Grab the host name portion of the URL for the
                    // friendly name for the server.
                    //
                    Uri uri = new Uri (dialog.ServerURL);

                    RegisteredServers.AddServer(uri.Host, dialog.ServerURL);

                    // Update our UI.
                    //
                    PopulateServerList();
                }
            }
        }

        private void ServerConfigForm_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
            System.Diagnostics.Process.Start("http://www.codeplex.com/UKVSTS/Wiki/View.aspx?title=Bug%20Details");
        }
    }
}